/**
 * products.js Created by Administrator on 2017/9/16.
 */

import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './mutationNames'

Vue.use(Vuex)

//定义state
const state = {
    //形状：[{id, name, description, image, price}, ...]
    all: [
        {id: 1, name: 'Box of macaroons', image: require('../assets/dianjigouwuche/images/product-01.jpg'), description: 'A very delicious macaroons ...', price: 19.20, inventory: 10},
        {id: 2, name: 'Cherry Straws',    image: require('../assets/dianjigouwuche/images/product-02.jpg'), description: 'A very delicious macaroons ...', price: 39.44, inventory: 10},
        {id: 3, name: 'COFFEE MACAROONS', image: require('../assets/dianjigouwuche/images/product-03.jpg'), description: 'A very delicious macaroons ...', price: 55.23, inventory: 10},
        {id: 4, name: 'FINETTI ONES',     image: require('../assets/dianjigouwuche/images/product-04.jpg'), description: 'A very delicious macaroons ...', price: 14.22, inventory: 10},
        {id: 5, name: 'MINTY DUO',        image: require('../assets/dianjigouwuche/images/product-05.jpg'), description: 'A very delicious macaroons ...', price: 29.12, inventory: 10},
        {id: 6, name: 'PISTACHIO',        image: require('../assets/dianjigouwuche/images/product-06.jpg'), description: 'A very delicious macaroons ...', price: 49.42, inventory: 10},
    ]
}

//定义getters -- 相当于Store的计算属性
const getters = {
    allProducts: function (state) {
        return state.all
    },
    getProductById: function (state) {
        return id=>state.all.find(product=>product.id === id)
    }
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
    [types.ADD_TO_CART]: function (state,id) {
        let product = state.all.find(product=>product.id === id)
        if(product && product.inventory > 0){
            product.inventory--;
        }
    },
    [types.REMOVE_FROM_CART]: function (state, id) {
        let product = state.all.find(product=>product.id === id)
        if(product) {
            product.inventory++;
        }
    },
    //payload: {product, count, oldcount}
    [types.UPDATE_PRODUCT_COUNT]: function (state, payload) {
        console.log('products.js UPDATE_PRODUCT_COUNT: ')
        console.log(payload)
        let product = state.all.find(product=>product.id === payload.product.id)
        if(product){
            product.inventory += payload.oldcount
            product.inventory -= payload.count;
        }
    }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
}

//导出Store
export default {
    state,
    getters,
    mutations,
    actions
};